﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Xml;

namespace CommonLib.WeiXin
{
    /// <summary>
    /// 获取并初始化微信数据
    /// </summary>
    public class wx
    {
        private CommonLib.WeiXin.Data data;

        public CommonLib.WeiXin.Data Data
        {
            get { return this.data; }
            set { this.data = value; }
        }

        public wx(string token)
        {
            check(token);
            if (HttpContext.Current.Request.HttpMethod.ToLower() == "post")
            {
                this.data = GetData();
            }
        }

        #region 效验消息的真实性
        /// <summary>
        /// 效验消息的真实性
        /// </summary>
        public void check(string token)
        {
            string signature = System.Web.HttpContext.Current.Request.QueryString["signature"];
            string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"];
            string echoStr = System.Web.HttpContext.Current.Request.QueryString["echoStr"];

            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp); //将token、timestamp、nonce三个参数进行字典排序

            string tmpStr = string.Join("", ArrTmp);
            tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");  //sha1
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    System.Web.HttpContext.Current.Response.Write(echoStr);
                    System.Web.HttpContext.Current.Response.End();
                }
            }
        }
        #endregion 效验消息的真实性

        #region 获取并设置数据

        /// <summary>
        /// 获取并设置数据
        /// </summary>
        /// <returns></returns>
        private CommonLib.WeiXin.Data GetData()
        {
            Stream s = HttpContext.Current.Request.InputStream;
            byte[] b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            string postStr = Encoding.UTF8.GetString(b);

            if (!string.IsNullOrEmpty(postStr))
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(postStr);
                XmlElement xml = doc.DocumentElement;
                XmlNode node = xml.SelectSingleNode("MsgType");

                var wxData = new CommonLib.WeiXin.Data();

                wxData.PostXml = postStr;
                wxData.ToUserName = xml.SelectSingleNode("ToUserName").InnerText;
                wxData.FromUserName = xml.SelectSingleNode("FromUserName").InnerText;
                wxData.CreateTime = xml.SelectSingleNode("CreateTime").InnerText;

                wxData.MsgType = node.InnerText;

                if (postStr.IndexOf("<MsgId>") > -1)
                {
                    wxData.MsgId = xml.SelectSingleNode("MsgId").InnerText;
                }
                //图片
                if (postStr.IndexOf("<PicUrl>") > -1)
                {
                    wxData.PicUrl = xml.SelectSingleNode("PicUrl").InnerText;
                }
                if (postStr.IndexOf("<MediaId>") > -1)
                {
                    wxData.MediaId = xml.SelectSingleNode("MediaId").InnerText;
                }

                //语音
                if (postStr.IndexOf("<Format>") > -1)
                {
                    wxData.Format = xml.SelectSingleNode("Format").InnerText;
                }
                if (postStr.IndexOf("<Recognition>") > -1)
                {
                    wxData.Recognition = xml.SelectSingleNode("Recognition").InnerText;
                }

                //视频 
                if (postStr.IndexOf("<ThumbMediaId>") > -1)
                {
                    wxData.ThumbMediaId = xml.SelectSingleNode("ThumbMediaId").InnerText;
                }

                //文本
                if (postStr.IndexOf("<Content>") > -1)
                {
                    wxData.Content = xml.SelectSingleNode("Content").InnerText;
                }
                //地理位置信息

                if (postStr.IndexOf("<Location_X>") > -1)
                {
                    wxData.Location_X = xml.SelectSingleNode("Location_X").InnerText;
                }
                if (postStr.IndexOf("<Location_Y>") > -1)
                {
                    wxData.Location_Y = xml.SelectSingleNode("Location_Y").InnerText;
                }
                if (postStr.IndexOf("<Scale>") > -1)
                {
                    wxData.Scale = xml.SelectSingleNode("Scale").InnerText;
                }
                if (postStr.IndexOf("<Label>") > -1)
                {
                    wxData.Label = xml.SelectSingleNode("Label").InnerText;
                }

                //链接地址
                if (postStr.IndexOf("<Title>") > -1)
                {
                    wxData.Title = xml.SelectSingleNode("Title").InnerText;
                }
                if (postStr.IndexOf("<Description>") > -1)
                {
                    wxData.Description = xml.SelectSingleNode("Description").InnerText;
                }
                if (postStr.IndexOf("<Url>") > -1)
                {
                    wxData.Url = xml.SelectSingleNode("Url").InnerText;
                }

                //事件推送
                if (postStr.IndexOf("<Event>") > -1)
                {
                    wxData.Event = xml.SelectSingleNode("Event").InnerText;
                }
                if (postStr.IndexOf("<EventKey>") > -1)
                {
                    wxData.EventKey = xml.SelectSingleNode("EventKey").InnerText;
                }
                return wxData;
            }
            return null;
        }

        #endregion 获取并设置数据

        #region 发送消息
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="Content">消息内容;news图文信息 需要组合好的一个串</param>
        /// <param name="msgType">消息类型 枚举类型</param>
        public void send(string Content, MsgType msgType)
        {
            StringBuilder str = new StringBuilder();
            if (msgType == MsgType.image)
            {

            }
            else if (msgType == MsgType.music)
            {

            }
            else if (msgType == MsgType.news)
            {
                str.Append(Content);
            }
            else if (msgType == MsgType.text)
            {
                str.Append("<Content><![CDATA[" + Content + "]]></Content>");
            }
            else if (msgType == MsgType.video)
            {

            }
            else if (msgType == MsgType.voice)
            {

            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<xml>");
            sb.Append("<ToUserName><![CDATA[" + this.Data.FromUserName + "]]></ToUserName>");
            sb.Append("<FromUserName><![CDATA[" + this.Data.ToUserName + "]]></FromUserName>");
            sb.Append("<CreateTime>" + ConvertDateTimeInt() + "</CreateTime>");
            sb.Append("<MsgType><![CDATA[" + msgType + "]]></MsgType>");

            sb.Append(str.ToString());

            sb.Append("</xml>");
            HttpContext.Current.Response.Write(sb.ToString());
        }


        private int ConvertDateTimeInt()
        {
            System.DateTime time = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)((DateTime.Now - time).TotalSeconds);
        }

        #endregion 发送消息
    }
}
